package com.ushahidi.android.app;

import java.util.LinkedList;
import java.util.List;
import java.util.Vector;

import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.google.android.maps.MapView;
import com.ushahidi.android.app.data.DeploymentProvider;
import com.ushahidi.android.app.data.IncidentsData;
import com.ushahidi.android.app.data.UshahidiDatabase;
import com.ushahidi.android.app.util.Util;

public class INeed extends DashboardActivity
{
    private TextView             mTextView;

    private ListView             mListView;

    //By OceanMaster
    //private MapView 		 mapView;
    //Guess reason : service related
    
    private ListIncidentAdapter ila;
    
    private List<IncidentsData> tmpIncidentsPile;
    
    private Bundle incidentsBundle;
    
    private static final int VIEW_INCIDENT = 3;

    private Button queryButton;
    //End
    private static final int     MENU_SEARCH     = 1;

    private final CharSequence[] items           = { "50", "100", "250", "500",
	    "750", "1000", "1500"               };

    private static final int     DIALOG_DISTANCE = 0;

    protected void onCreate(Bundle savedInstanceState)
    {
	super.onCreate(savedInstanceState);
	
	ila = new ListIncidentAdapter(this);
	tmpIncidentsPile = new LinkedList<IncidentsData>();
	incidentsBundle = new Bundle();
	 
	 
	setContentView(R.layout.i_need);
	setTitleFromActivityLabel(R.id.title_text);

	mTextView = (TextView) findViewById(R.id.search);
	mListView = (ListView) findViewById(R.id.resources_list);
	queryButton = (Button) findViewById(R.id.query_button);
	//mapView   = (MapView)  findViewById(R.id.location_map);

	queryButton.setOnClickListener(new View.OnClickListener()
	{
	    public void onClick(View v)
	    {
		if (!TextUtils.isEmpty(mTextView.getText()))
		    {
			Log.v("Oceanmaster", "I need text changed : "+mTextView.getText().toString());
		    	showResults(mTextView.getText().toString());
		    }
		    else
		    {
			showResults();
		    }
	    }
	});
//	mTextView.setOnFocusChangeListener(new View.OnFocusChangeListener()
//        {
//
//	    public void onFocusChange(View v, boolean hasFocus)
//	    {
//	        if (!hasFocus)
//	        {
//		    if (!TextUtils.isEmpty(mTextView.getText()))
//		    {
//			Log.v("Oceanmaster", "I need text changed : "+mTextView.getText().toString());
//		    	showResults(mTextView.getText().toString());
//		    }
//		    else
//		    {
//			showResults();
//		    }
//	        }
//	    }
//        });
	
	showResults();
//	mTextView.addTextChangedListener(new TextWatcher()
//	{
//
//	    public void afterTextChanged(Editable arg0)
//	    {
//		//Log.v("Oceanmaster", "I need text changed : "+arg0.toString());
//	    }
//
//	    public void beforeTextChanged(CharSequence s, int start, int count,
//		    int after)
//	    {
//		// TODO Auto-generated method stub
//	    }
//
//	    public void onTextChanged(CharSequence s, int start, int before,
//		    int count)
//	    {
////		Cursor cursor = showResults(mTextView.getText().toString());
////
////		// Specify the columns we want to display in the result
////		String[] from = new String[] {
////		        UshahidiDatabase.DEPLOYMENT_NAME,
////		        UshahidiDatabase.DEPLOYMENT_DESC,
////		        UshahidiDatabase.DEPLOYMENT_URL };
////
////		// Specify the corresponding layout elements where we want the
////		// columns to go
////		int[] to = new int[] { R.id.deploy_name, R.id.deploy_desc,
////		        R.id.deploy_url };
////
////		// Create a simple cursor adapter for the details of the
////		// deployment and apply
////		// them to the ListView
////		if (cursor != null)
////		{
////		    SimpleCursorAdapter deployments = new SimpleCursorAdapter(
////			    INeed.this,
////			    R.layout.deployment_search_result, cursor, from, to);
////		    mListView.setAdapter(deployments);
////		}
////		else
////		{
////		    showResults();
////		}
//	    }
//	});
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
	menu.add(0, MENU_SEARCH, 0, R.string.search_label)
	        .setIcon(android.R.drawable.ic_search_category_default)
	        .setAlphabeticShortcut(SearchManager.MENU_KEY);

	return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
	switch (item.getItemId())
	{
	    case MENU_SEARCH:
		onSearchRequested();
		return true;
	}
	return super.onOptionsItemSelected(item);
    }

    /**
     * Searches the dictionary and displays results for the given query.
     * 
     * @param query
     *            The search query
     */
    private void showResults(Cursor cursor)
    {
    	String title;
        String status;
        String date;
        String description;
        String location;
        String categories;
        String media;
        String image;
        
        String thumbnails[];
        Drawable d = null;

        if (cursor.moveToFirst()) {
            int idIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_ID);
            int titleIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_TITLE);
            int dateIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_DATE);
            int verifiedIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_VERIFIED);
            int locationIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_LOC_NAME);

            int descIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_DESC);

            int categoryIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_CATEGORIES);

            int mediaIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_MEDIA);

            int imageIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_IMAGE);

            int latitudeIndex = cursor
                    .getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_LOC_LATITUDE);

            int longitudeIndex = cursor
                    .getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_LOC_LONGITUDE);

            ila.removeItems();
            ila.notifyDataSetChanged();
            tmpIncidentsPile.clear();

            do {

                IncidentsData incidentData = new IncidentsData();
                tmpIncidentsPile.add(incidentData);
                ListIncidentText listText = new ListIncidentText();

                int id = Util.toInt(cursor.getString(idIndex));
                incidentData.setIncidentId(id);
                incidentData.setIncidentLocLatitude(cursor.getString(latitudeIndex));
                incidentData.setIncidentLocLongitude(cursor.getString(longitudeIndex));

                title = cursor.getString(titleIndex);
                incidentData.setIncidentTitle(title);
                listText.setTitle(Util.capitalize(title));

                description = cursor.getString(descIndex);
                incidentData.setIncidentDesc(description);
                listText.setDesc(description);

                categories = cursor.getString(categoryIndex);
                incidentData.setIncidentCategories(categories);
                listText.setCategories(Util.capitalize(categories));

                location = cursor.getString(locationIndex);
                incidentData.setIncidentLocation(location);
                listText.setLocation(Util.capitalize(location));

                date = Util.formatDate("yyyy-MM-dd HH:mm:ss", cursor.getString(dateIndex),
                        "MMMM dd, yyyy 'at' hh:mm:ss aaa");

                incidentData.setIncidentDate(date);
                listText.setDate(date);

                media = cursor.getString(mediaIndex);
                incidentData.setIncidentThumbnail(media);
                listText.setMedia(media);

                thumbnails = media.split(",");
                // TODO do a proper check for thumbnails
                if (!TextUtils.isEmpty(thumbnails[0])) {
                    d = ImageManager.getImages(thumbnails[0]);
                } else {
                    d = null;
                }

                listText.setThumbnail(d == null ? getResources().getDrawable(
                        R.drawable.ushahidi_report_icon) : d);

                image = cursor.getString(imageIndex);
                incidentData.setIncidentImage(image);

                status = Util.toInt(cursor.getString(verifiedIndex)) == 0 ? getString(R.string.report_unverified)
                        : getString(R.string.report_verified);
                incidentData.setIncidentVerified(Util.toInt(cursor.getString(verifiedIndex)));
                listText.setStatus(status);

                listText.setId(id);
                listText.setArrow(getResources().getDrawable(R.drawable.ushahidi_arrow));
                ila.addItem(listText);

            } while (cursor.moveToNext());
        }

        cursor.close();
        ila.notifyDataSetChanged();
        mListView.setAdapter(ila);
        
        mListView.setOnItemClickListener(new OnItemClickListener()
	    {
            	public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            	{
                    
                incidentsBundle.putInt("id", tmpIncidentsPile.get(position).getIncidentId());
                incidentsBundle.putString("title", tmpIncidentsPile.get(position).getIncidentTitle());
                incidentsBundle.putString("desc", tmpIncidentsPile.get(position).getIncidentDesc());
                incidentsBundle.putString("longitude", tmpIncidentsPile.get(position)
                        .getIncidentLocLongitude());
                incidentsBundle.putString("latitude", tmpIncidentsPile.get(position)
                        .getIncidentLocLatitude());
                incidentsBundle.putString("category", tmpIncidentsPile.get(position)
                        .getIncidentCategories());
                incidentsBundle.putString("location", tmpIncidentsPile.get(position)
                        .getIncidentLocation());
                incidentsBundle.putString("date", tmpIncidentsPile.get(position).getIncidentDate());
                incidentsBundle.putString("media", tmpIncidentsPile.get(position)
                        .getIncidentThumbnail());
                incidentsBundle.putString("image", tmpIncidentsPile.get(position).getIncidentImage());
                incidentsBundle.putString("status", ""
                        + tmpIncidentsPile.get(position).getIncidentVerified());

                Intent intent = new Intent(INeed.this, ViewIncidents.class);
                intent.putExtra("incidents", incidentsBundle);
                startActivityForResult(intent, VIEW_INCIDENT);
                setResult(RESULT_OK, intent);

            }

	    });
    }

    /**
     * Searches the dictionary and displays results for the given query.
     * 
     * @param query
     *            The search query
     */
    private void showResults(String query)
    {
	String[] queries = query.trim().replaceAll("/s+", " ").split(" ");
	
	Log.v("Oceanmaster", "Unified Query is ["+Util.implode(queries)+"]");
	
	
	//TODO search name and description
	// currently just search name
	// potantial BUG : should be limited to resource incidents.
        Cursor cursor = UshahidiApplication.mDb.fetchIncidentsByCategories(queries);
        showResults(cursor);
    }
    
    private void showResults()
    {
	Cursor cursor = UshahidiApplication.mDb.fetchResourceIncidents();
        showResults(cursor);
	
	//totally rewrite 
	
//	    // Specify the columns we want to display in the result
//	    String[] from = new String[] { UshahidiDatabase.DEPLOYMENT_NAME,
//		    UshahidiDatabase.DEPLOYMENT_DESC,
//		    UshahidiDatabase.DEPLOYMENT_URL };
//
//	    // Specify the corresponding layout elements where we want the
//	    // columns to go
//	    int[] to = new int[] { R.id.deployment_list_name,
//		    R.id.deployment_list_desc, R.id.deployment_list_url };
//
//	    // Create a simple cursor adapter for the definitions and apply them
//	    // to the ListView
//	    SimpleCursorAdapter deployments = new SimpleCursorAdapter(this,
//		    R.layout.deployment_list, cursor, from, to);
//	    mListView.setAdapter(deployments);
//
//	    // Define the on-click listener for the list items
//	    mListView.setOnItemClickListener(new OnItemClickListener()
//	    {
//		public void onItemClick(AdapterView<?> parent, View view,
//		        int position, long id)
//		{
//		    // TODO: do something when the list item is clicked.
//		}
//	    });
    }

    /**
     * Create an alert dialog
     */

    protected void createDialog(int d)
    {
	switch (d)
	{
	    case DIALOG_DISTANCE:
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Select distance in km");
		builder.setItems(items, new DialogInterface.OnClickListener()
		{
		    public void onClick(DialogInterface dialog, int item)
		    {

		    }
		});

		AlertDialog alert = builder.create();
		alert.show();
	}

    }

    /**
     * Do something when the refresh icon is pressed
     */
    @Override
    public void onRefreshReports(View v)
    {
	createDialog(DIALOG_DISTANCE);
    }

    public void onClickHome(View v)
    {
	goHome(this);
    }

    public void goHome(Context context)
    {
	final Intent intent = new Intent(context, Ushahidi.class);
	intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	context.startActivity(intent);
    }
    
}
